﻿using AduSkin.Controls.Metro;
using HsServerHa.Common;
using HsServerHa.Common.Auth;
using HsServerHa.Core.Http;
using HsServerHa.Entity.Models;
using HsServerHa.Utility;
using HsServerHa.Utility.DataHelper;
using HsServerHa.Utility.HttpHelper;
using HsServerHa.Utility.NetWork;
using HsServerHa.Utility.SQLite;
using Microsoft.Win32;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Management;
using System.Net.NetworkInformation;
using System.Threading.Tasks;
using System.Windows;

namespace HsServerHa.UserControls
{
    /// <summary>
    /// MasterSlaveSwitch.xaml 的交互逻辑
    /// </summary>
    public partial class MasterSlaveSwitch : System.Windows.Controls.UserControl
    {
        public MasterSlaveSwitch()
        {
            InitializeComponent();
            initData();

        }
        public void initData()
        {
            try
            {

                if (App.isMaster != null)
                {
                    this.btn_Setting.Visibility = Visibility.Visible;
                    if (App.isMaster.Value)
                    {
                        this.zj_grid.Visibility = Visibility.Visible;
                        this.cj_grid.Visibility = Visibility.Hidden;
                        this.btn_Setting.Content = "是否切换成从机";
                    }
                    else
                    {
                        this.zj_grid.Visibility = Visibility.Hidden;
                        this.cj_grid.Visibility = Visibility.Visible;
                        this.btn_Setting.Content = "是否切换成主机";
                    }
                }
                else
                {
                    this.btn_Setting.Visibility = Visibility.Hidden;
                }
            }
            catch
            {

            }
        }
        private async void btn_Setting_Click(object sender, RoutedEventArgs e)
        {
            #region 授权验证
            if (!AuthorizationVerification.IsVerification())
            {
                AduMessageBoxs.Show("授权到期！");
                return;
            }

            #endregion
            var str = this.btn_Setting.Content.ToString().Replace("是否", "");
            MessageBoxResult dr = AduMessageBox.ShowOKCancel($"你确定{str}吗？", "系统提示!", "确定", "取消");
            if (dr == MessageBoxResult.OK)
            {
                if (App.isMaster != null)
                {
                    this.loading.Visibility = Visibility.Visible;
                    this.btn_Setting.IsEnabled = false;
                    List<MasterSlaveBindEntity> listBind = SQLiteHelper.Table<MasterSlaveBindEntity>().ToList();
                    var bindFirst = listBind.FirstOrDefault();
                    if (bindFirst != null)
                    {
                        if (string.IsNullOrEmpty(bindFirst.SlaveIP)|| string.IsNullOrEmpty(bindFirst.MasterIP))
                        {
                            AduMessageBoxs.Show("未配置主从关系，无法切换！");
                            this.loading.Visibility = Visibility.Hidden;
                            return;
                        }
                           

                        if (!App.isMaster.Value)
                        {
                            if (!NetWorkHelper.IsPingIP(bindFirst.MasterIP))
                            {//如果PING不通就直接切换成主机
                                MasterSlaveSwitchHelper.SwitchMaster();


                                AduMessageBoxs.Show("切换主机成功！");
                                this.loading.Visibility = Visibility.Hidden;
                                this.btn_Setting.IsEnabled = true;
                                LoggerHelper.SetInfo("将从机切换成了主机", "主从切换");
                                if (App.isMaster.Value)
                                {
                                    this.zj_grid.Visibility = Visibility.Visible;
                                    this.cj_grid.Visibility = Visibility.Hidden;
                                    this.btn_Setting.Content = "是否切换成从机";
                                }
                                else
                                {
                                    this.zj_grid.Visibility = Visibility.Hidden;
                                    this.cj_grid.Visibility = Visibility.Visible;
                                    this.btn_Setting.Content = "是否切换成主机";
                                }
                                return;
                            }
                        }
                        else
                        {
                            if (!NetWorkHelper.IsPingIP(bindFirst.SlaveIP))
                            {//如果PING不通就直接切换成从机
                                MasterSlaveSwitchHelper.SwitchSlave();
                                AduMessageBoxs.Show("切换成功！");
                                LoggerHelper.SetInfo("将主机切换成了从机", "主从切换");
                                if (App.isMaster.Value)
                                {
                                    this.zj_grid.Visibility = Visibility.Visible;
                                    this.cj_grid.Visibility = Visibility.Hidden;
                                    this.btn_Setting.Content = "是否切换成从机";
                                }
                                else
                                {
                                    this.zj_grid.Visibility = Visibility.Hidden;
                                    this.cj_grid.Visibility = Visibility.Visible;
                                    this.btn_Setting.Content = "是否切换成主机";
                                }

                                this.loading.Visibility = Visibility.Hidden;
                                this.btn_Setting.IsEnabled = true;
                                return;
                            }
                        }
                        if (App.isMaster.Value)
                        {
                            if (string.IsNullOrEmpty(bindFirst.SlaveIP))
                            {
                                AduMessageBoxs.Show("从机不存在！");
                                LoggerHelper.SetInfo("切换从机失败->从机不存在", "主从切换");
                                this.loading.Visibility = Visibility.Hidden;
                                this.btn_Setting.IsEnabled = true;
                                return;
                            }
                            //请求从机接口
                            var path = $"http://{bindFirst.SlaveIP}:{ConfigurationManager.AppSettings["HttpPort"]?.ToString() ?? "6601"}/" + ConfigurationManager.AppSettings["postSwitchMaster"]?.ToString() ?? "postSwitchMaster";
                            var result = HttpHelpers.PostToJson<HttpResponseResultModel<object>>(path).Result;
                            if (result != null)
                            {
                                if (result.IsSuccess)
                                {
                                    #region 数据库主切换成从
                                    //var sql = "SELECT * FROM SQLManage where IsEnable='是'";
                                    //var Sqldt = DbHelperSQLite.Query(sql)?.Tables?[0];
                                    //List<SQLManageEntity> Sqllist = DataHelpers.ConvertToModel<SQLManageEntity>(Sqldt);
                                    List<SQLManageEntity> Sqllist = SQLiteHelper.Table<SQLManageEntity>().Where(x => x.IsEnable == "是").ToList();
                                    foreach (var item in Sqllist)
                                    {
                                        var DBConnectionStr = ConfigurationManager.AppSettings["DBConnectionString"].ToString();
                                        DBConnectionStr = DBConnectionStr.Replace("#IPAddress#", App.CurrIP + "," + item.Port);
                                        DBConnectionStr = DBConnectionStr.Replace("#DBName#", "master");
                                        DBConnectionStr = DBConnectionStr.Replace("#UserId#", item.UserId);
                                        DBConnectionStr = DBConnectionStr.Replace("#UserPwd#", item.UserPwd);
                                        DbHelperSQL db = new DbHelperSQL(DBConnectionStr);
                                        Task.Run(() =>
                                        {
                                            try
                                            {
                                                db.ExecuteSql($"USE master;  ALTER DATABASE [{item.DBName}] SET PARTNER FAILOVER");
                                            }
                                            catch (Exception ex)
                                            {
                                                LoggerHelper.Error("主切从异常：" + ex.Message);
                                            }
                                        });
                                    }
                                    #endregion
                                    MasterSlaveSwitchHelper.SwitchSlave();
                                    AduMessageBoxs.Show("切换成功！");
                                    LoggerHelper.SetInfo("将主机切换成了从机", "主从切换");
                                    if (App.isMaster.Value)
                                    {
                                        this.zj_grid.Visibility = Visibility.Visible;
                                        this.cj_grid.Visibility = Visibility.Hidden;
                                        this.btn_Setting.Content = "是否切换成从机";
                                    }
                                    else
                                    {
                                        this.zj_grid.Visibility = Visibility.Hidden;
                                        this.cj_grid.Visibility = Visibility.Visible;
                                        this.btn_Setting.Content = "是否切换成主机";
                                    }

                                    this.loading.Visibility = Visibility.Hidden;
                                    this.btn_Setting.IsEnabled = true;

                                    ////主切从重置Mac地址                                   
                                    //List<MultipleNetworkCardManageEntity> list = await SQLiteHelper.TableAsync<MultipleNetworkCardManageEntity>().Where(x => x.IsEnable == "是").ToListAsync().ConfigureAwait(false);
                                    //var MultipleNetworkCard = list.FirstOrDefault();
                                    //if (MultipleNetworkCard != null)
                                    //{
                                    //    ReSetMacAddress(MultipleNetworkCard.NetworkCardName, GetRandMac());
                                    //    AduMessageBoxs.Show("重机Mac地址重置成功！");
                                    //}

                                    return;
                                }
                                else
                                {
                                    AduMessageBoxs.Show("切换从机失败！");
                                    LoggerHelper.SetInfo("切换从机失败", "主从切换");
                                    this.loading.Visibility = Visibility.Hidden;
                                    this.btn_Setting.IsEnabled = true;
                                    return;
                                }
                            }
                            else
                            {
                                AduMessageBoxs.Show("切换从机失败！");
                                LoggerHelper.SetInfo("切换从机失败", "主从切换");
                                this.loading.Visibility = Visibility.Hidden;
                                this.btn_Setting.IsEnabled = true;
                                return;
                            }

                           
                        }
                        else
                        {
                            var path = $"http://{bindFirst.MasterIP}:{ConfigurationManager.AppSettings["HttpPort"]?.ToString() ?? "6601"}/";
                            var isCzSQL = false;
                            List<SQLManageEntity> Sqllist = SQLiteHelper.Table<SQLManageEntity>().Where(x => x.IsEnable == "是").ToList();
                            if (Sqllist.Count > 0)
                            {
                                isCzSQL = true;

                            }
                            if (isCzSQL)
                            {
                                //通知主机切换数据库配置
                                var SwatchResult = HttpHelpers.PostToJson<HttpResponseResultModel<object>>(path + ConfigurationManager.AppSettings["postSwatchSQLData"]?.ToString() ?? "postSwatchSQLData").Result;
                                if (SwatchResult == null)
                                {
                                    AduMessageBoxs.Show("切换主机失败，数据库出现异常！");
                                    return;
                                }
                                if (SwatchResult.IsSuccess)
                                {
                                    //请求主机接口

                                    var result = HttpHelpers.PostToJson<HttpResponseResultModel<object>>(path + ConfigurationManager.AppSettings["postSwitchSlave"]?.ToString() ?? "postSwitchSlave").Result;
                                    if (result != null)
                                    {
                                        if (result.IsSuccess)
                                        {
                                            MasterSlaveSwitchHelper.SwitchMaster();
                                            AduMessageBoxs.Show("切换主机成功！");
                                            this.loading.Visibility = Visibility.Hidden;
                                            this.btn_Setting.IsEnabled = true;
                                            LoggerHelper.SetInfo("将从机切换成了主机", "主从切换");

                                        }
                                        else
                                        {
                                            AduMessageBoxs.Show("切换主机失败！");
                                            LoggerHelper.SetInfo("切换主机失败", "主从切换");
                                            this.loading.Visibility = Visibility.Hidden;
                                            this.btn_Setting.IsEnabled = true;
                                            return;
                                        }
                                    }
                                    else
                                    {
                                        AduMessageBoxs.Show("切换主机失败！");
                                        LoggerHelper.SetInfo("切换主机失败", "主从切换");
                                        this.loading.Visibility = Visibility.Hidden;
                                        this.btn_Setting.IsEnabled = true;
                                        return;
                                    }
                                }

                            }
                            else
                            {
                                //请求主机接口

                                var result = HttpHelpers.PostToJson<HttpResponseResultModel<object>>(path + ConfigurationManager.AppSettings["postSwitchSlave"]?.ToString() ?? "postSwitchSlave").Result;
                                if (result != null)
                                {
                                    if (result.IsSuccess)
                                    {
                                        MasterSlaveSwitchHelper.SwitchMaster();
                                        AduMessageBoxs.Show("切换主机成功！");
                                        this.loading.Visibility = Visibility.Hidden;
                                        this.btn_Setting.IsEnabled = true;
                                        LoggerHelper.SetInfo("将从机切换成了主机", "主从切换");

                                        //从机切换成主机
                                        //List<MultipleNetworkCardManageEntity> list = await SQLiteHelper.TableAsync<MultipleNetworkCardManageEntity>().Where(x => x.IsEnable == "是").ToListAsync().ConfigureAwait(false);
                                        //var MultipleNetworkCard = list.FirstOrDefault();
                                        //if (MultipleNetworkCard != null)
                                        //{
                                        //    ReSetMacAddress(MultipleNetworkCard.NetworkCardName, MultipleNetworkCard.MAC);
                                        //    AduMessageBoxs.Show("主机Mac地址重置成功！");
                                        //}
                                    }
                                    else
                                    {
                                        AduMessageBoxs.Show("切换主机失败！");
                                        LoggerHelper.SetInfo("切换主机失败", "主从切换");
                                        this.loading.Visibility = Visibility.Hidden;
                                        this.btn_Setting.IsEnabled = true;
                                        return;
                                    }
                                }
                                else
                                {
                                    AduMessageBoxs.Show("切换主机失败！");
                                    LoggerHelper.SetInfo("切换主机失败", "主从切换");
                                    this.loading.Visibility = Visibility.Hidden;
                                    this.btn_Setting.IsEnabled = true;
                                    return;
                                }
                            }

                           
                        }
                    }
                    else
                    {
                        LoggerHelper.SetInfo("切换失败", "主从切换");
                    }
                }
                initData();
            }
        }

        private ManagementObject? GetNetAdapter(string name)
        {
            //name = "Intel(R) Wi-Fi 6 AX201 160MHz";
            using (ManagementClass mc = new ManagementClass("Win32_NetworkAdapter"))
            {
                var ns = mc.GetInstances().Cast<ManagementObject>().Where(x => x["NetEnabled"] != null && (bool)x["NetEnabled"] == true).ToList();
                return ns.Where(x => (string)x["Name"] == name).FirstOrDefault();
            }
        }


    }
}
